import store from "../../store";
import {
  CHANGE_WS_STATE
} from "../../store/events";

import messageDistributer from "./messageDistributer";

import ADDRESS from "../../assets/backendApi";

let ws = null;

export function connectWs() {
  const HOST = ADDRESS.ws + `/connect/${store.state.roomid}/${store.state.username}/`;

  ws = new WebSocket(HOST);

  ws.onopen = function () {
    store.dispatch(CHANGE_WS_STATE, {
      wsState: 1
    });
  };

  ws.onmessage = function (evt) {
    // 提取消息内容
    let data = JSON.parse(evt.data);
    if (typeof data.data === "string") {
      data = JSON.parse(data.data);
    } else if (typeof data.data === "object") {
      data = data.data;
    } else {
      throw "Error: 服务端消息内容错误";
    }
    // 分类处理消息
    if (data.type === "init") {
      if (store.state.wsState === 2) {
        throw "Error: 重复初始化房间";
      }
      for (const message of data.messages) {
        messageDistributer(message, true);
      }
      store.dispatch(CHANGE_WS_STATE, {
        wsState: 2
      });
    } else {
      messageDistributer(data);
    }
  };

  ws.onclose = function () {
    store.dispatch(CHANGE_WS_STATE, {
      wsState: 0
    });
  };
}

export function sendWsMsg(msg) {
  if (!ws) throw "Error: 未开启WebSocket连接";
  if (typeof msg === "object") {
    msg = JSON.stringify(msg);
  } else if (typeof msg !== "string") {
    throw "Error: 要发送的WebSocket消息格式错误";
  }
  ws.send(msg);
}

export function closeWs() {
  if (!ws) return;
  ws.close();
}